package com.c.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.c.entity.Permission;
import com.c.entity.Role;
import com.c.mapper.PermissionMapper;
import com.c.service.PermissionService;
import com.c.utils.MessageConstant;
import com.c.utils.PageResult;
import com.c.utils.QueryPageBean;
import com.c.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wangxiangli
 * @create 2022-12-25-12:34
 */
@Service
@Transactional
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    /**
     * 权限分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        IPage<Permission> pagePermission=new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        QueryWrapper<Permission> wrapper=new QueryWrapper();
        String queryString = queryPageBean.getQueryString();
        //判断条件值是否为空，如果不为空拼接条件
        if (queryPageBean.getQueryString() != null && queryPageBean.getQueryString().length() > 0) {
            queryString = queryPageBean.getQueryString().trim();// 去除查询条件首尾空格
            wrapper.like("name",queryString);
            wrapper.or().like("keyword",queryString);
        }
        IPage page1 = baseMapper.selectPage(pagePermission, wrapper);
        return new PageResult(page1.getTotal(),page1.getRecords());
    }
    /**
     * 新增权限
     *
     * @param permission
     */
    @Override
    public Result add(Permission permission) {
        //先判断权限关键字是否存在（t_permission）
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("keyword",permission.getKeyword());
        Permission permission1 = baseMapper.selectOne(wrapper);
        if (permission1 != null) {
            return new Result(false, "该权限关键字已经存在,无法创建");
        } else {
            baseMapper.insert(permission);
            return new Result(true, MessageConstant.ADD_PERMISSION_SUCCESS);
        }
    }

    /**
     * 根据ID删除权限
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        //判断当前权限是否已经关联到角色
        long count = baseMapper.findCountByCheckPermissionId(id);
        if (count > 0) {
            return new Result(false, "此权限正在使用,无法删除");
        }
        baseMapper.deleteById(id);
        return new Result(true, MessageConstant.DELETE_PERMISSION_SUCCESS);
    }
}
